package com.squirrel.serialportcore.utils;

/**
 * 字节工具
 *
 * @author Squbi
 * @date 2021/2/25 17:57
 */
public class ByteUtils {
    private ByteUtils() {
    }

    /**
     * 合并数组
     *
     * @param firstArray  第一个数组
     * @param secondArray 第二个数组
     * @return 合并后的数组
     */
    public static byte[] concat(byte[] firstArray, byte[] secondArray) {
        if (firstArray == null || secondArray == null) {
            if (firstArray != null) {
                return firstArray;
            }
            return secondArray;
        }
        byte[] bytes = new byte[firstArray.length + secondArray.length];
        System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);
        System.arraycopy(secondArray, 0, bytes, firstArray.length, secondArray.length);
        return bytes;
    }

    /**
     * 字节数组转字符串
     *
     * @author Squbi
     * @date 2021/2/24 10:44
     */
    public static String byte2String(byte[] b) {
        StringBuilder sbf = new StringBuilder();
        for (byte value : b) {
            String hex = Integer.toHexString(value & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sbf.append(hex.toUpperCase()).append("  ");
        }
        return sbf.toString().trim();
    }

    /**
     * 16转10计算
     */
    public static long getNum(String num1, String num2) {
        return Long.parseLong(num1, 16) * 256 + Long.parseLong(num2, 16);
    }

    /**
     * byte[]进行拼接
     *
     * @author Squbi
     * @date 2021/2/24 16:34
     */
    public static byte[] addByte(byte[] a, byte[] b) {
        byte[] c = new byte[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }

    public static byte[] addByte(byte[] a, byte b) {
        byte[] c = new byte[a.length + 1];
        System.arraycopy(a, 0, c, 0, a.length);
        c[c.length - 1] = b;
        return c;
    }

    public static byte[] addByte(byte a, byte[] b) {
        byte[] c = new byte[b.length + 1];
        System.arraycopy(b, 0, c, 1, b.length);
        c[0] = a;
        return c;
    }

    /**
     * string 转 byte[] 注意用空格分隔
     *
     * @author Squbi
     * @date 2021/3/1 10:30
     */
    public static byte[] string2Byte(String order) {
        String[] str = order.split(" ");
        if (str.length < 1) {
            return new byte[0];
        }
        byte[] bs = new byte[str.length];
        for (int i = 0; i < str.length; i++) {
            bs[i] = (byte) Integer.parseInt(str[i], 16);
        }
        return bs;
    }
}
